package com.macro.mall.tiny.modules.basic;

import cn.hutool.core.net.URLEncodeUtil;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.api.ResultCode;
import com.macro.mall.tiny.component.tencent.CosComponent;
import com.macro.mall.tiny.modules.pms.model.PmsCoolToolBrand;
import com.macro.mall.tiny.modules.pms.service.PmsCoolToolBrandService;
import com.macro.mall.tiny.modules.pms.service.PmsFactoryDataService;
import com.macro.mall.tiny.modules.ums.dto.FileUploadDto;
import com.macro.mall.tiny.modules.ums.model.UmsAdmin;
import com.macro.mall.tiny.modules.ums.model.UmsMember;
import com.macro.mall.tiny.modules.ums.service.UmsAdminService;
import com.macro.mall.tiny.security.util.JwtTokenUtil;
import com.macro.mall.tiny.security.util.MemberContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * MinIO对象存储管理Controller
 * Created by macro on 2019/12/25.
 */
@RestController
@Api(tags = "COSController")
@Tag(name = "COSController", description = "对象存储管理")
@RequestMapping("/minio")
public class COSController {


    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UmsAdminService umsAdminService;

    private static final Logger LOGGER = LoggerFactory.getLogger(COSController.class);
    /**
     * pms_brand 品牌logo ✅
     * pms_calculator 计算器logo
     * pms_category  品类 ✅
     * pms_cool_tool 制冷云 icon 和 内容
     * pms_cool_tool_brand 制冷云品牌
     * pms_electric_master_data 电工大师资料
     * pms_point_light 指示灯 ✅
     * pms_factory_data 厂家资料 ✅
     * pms_ad 广告图
     */
    static Map<Integer, String> UPLOAD_MAP = new HashMap<Integer, String>() {
        {
            put(1, "logo/"); //品牌  pms_brand  ✅
            put(2, "category/"); //品类 pms_category ✅
            put(3, "指示灯/"); //指示灯 指示灯下面有品牌分类
            put(4, "厂家资料/"); //厂家资料 ✅
            put(5, "说明书/"); //制冷云 制冷云下面有品牌分类
            put(6, "factoryCover/");// 厂家资料的封面 ✅
            put(7, "说明书/cover/"); // 说明书的封面 ✅
            put(8, "member/icon/"); // 用户头像 ✅
            put(9, "ad/"); // 广告图
            put(10,"electricMaster/") ; // 电工大师资料
            put(11,"other/") ; // 其他
            put(12,"维修资料/");
            put(13,"control/");
            put(14,"controlBrand/");
            put(15,"coolToolPDF/");

        }

    };


    /**
     * todo 需要权限控制的地方
     * pms_calculator
     * pms_cool_tool（制冷云）
     * pms_electric_master_data
     * pms_factory_data
     */
    @Autowired
    private CosComponent cosComponent;

    @Autowired
    private PmsCoolToolBrandService pmsCoolToolBrandService;


    @ApiOperation("文件上传")
    @PostMapping("/cosUpload")
    public CommonResult<FileUploadDto> uploadFile(@RequestParam MultipartFile file,
                                                  @ApiParam("前置路径(第一层路径不用带/ 就是不以/开头) 只要用于有分类的数据 如 指示灯 制冷云 厂家资料 前置路径填目录层级") @RequestParam(required = false) String levelPath,
                                                  @ApiParam("1 品牌 2 品类 3 指示灯 4 厂家资料 5 制冷云 " +
                                                          "6 厂家资料封面 7 制冷云封面 8用户头像 9广告图 10 电工大师资料 11其他 12维修数据 13工控数据  14 工控数据品牌 15 cooltool pdf文件" )
                                                  @RequestParam Integer type) {
        try {
            if (type == 5){
                if (StringUtils.isEmpty(levelPath)){
                    return CommonResult.failed("制冷云必须填写品牌分类");
                }
                String[] split = levelPath.split("/");
                PmsCoolToolBrand pmsCoolToolBrandServiceOne = pmsCoolToolBrandService.getOne(new QueryWrapper<>(new PmsCoolToolBrand()).eq("name",split[0]));
                levelPath = levelPath.replace(split[0],pmsCoolToolBrandServiceOne.getId().toString());
            }
            String prefixPath = UPLOAD_MAP.get(type);
            if (levelPath == null) {
                levelPath = "";
            }
            levelPath = prefixPath + levelPath;
            String viewPath = cosComponent.uploadFile(file, levelPath);
            FileUploadDto fileUploadDto = new FileUploadDto();
            fileUploadDto.setName(file.getOriginalFilename());
            fileUploadDto.setUrl(URLEncodeUtil.encode(viewPath));
            // 调用 COSService 上传文件
            return CommonResult.success(fileUploadDto);
        } catch (Exception e) {
            return CommonResult.failed("文件上传失败：" + e.getMessage());
        }
    }

    @Autowired
    private PmsFactoryDataService factoryDataService;

    @ApiOperation("获取文件 展示不使用 下个版本再说")
    @GetMapping("/cosGet")
    /**
     * https://document-1328890941.cos.ap-shanghai.myqcloud.com/logo/艾美特.png
     */
    public void getFile(@RequestParam String path,
                        @RequestParam Integer type,
                        @RequestHeader(required = false, value = "authorization") String authorization,
                        HttpServletResponse response) throws IOException {
        UmsMember member = MemberContext.getMember();
        if (member == null && authorization == null) {
            CommonResult<Object> failed = CommonResult.failed(ResultCode.FORBIDDEN);
            response.getOutputStream().write(JSON.toJSONString(failed).getBytes());
        }
        if (StringUtils.isNotEmpty(authorization)) {
            try {
                String adminUsername = jwtTokenUtil.getUserNameFromToken(authorization.replace("Bearer ", ""));
                UmsAdmin admin = umsAdminService.getAdminByUsername(adminUsername);
                cosComponent.downloadFile(path, response);
            } catch (Exception e) {
                CommonResult<Object> failed = CommonResult.failed(ResultCode.FORBIDDEN);
                response.getOutputStream().write(JSON.toJSONString(failed).getBytes());
            }
        }
        if (member != null) {
            if (member.getOpenId() == null) {
                CommonResult<Object> failed = CommonResult.failed(ResultCode.FORBIDDEN);
                response.getOutputStream().write(JSON.toJSONString(failed).getBytes());
            }
            cosComponent.downloadFile(path, response);
        }

    }


    @ApiOperation("url转COS图片")
    @PostMapping("/cosUploadByUrl")
    public CommonResult<FileUploadDto> uploadFileByUrl(@RequestParam String url, @RequestParam String openId) {
        try {
            String path = UPLOAD_MAP.get(8);

            String viewPath = cosComponent.uploadMemberIcon(url, openId, path);
            FileUploadDto fileUploadDto = new FileUploadDto();
            fileUploadDto.setUrl(viewPath);
            // 调用 COSService 上传文件
            return CommonResult.success(fileUploadDto);
        } catch (Exception e) {
            return CommonResult.failed("文件上传失败：" + e.getMessage());
        }
    }


}
